package com.yxcz.serviceImpl;

import java.util.ArrayList;
import java.util.HashMap;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yxcz.dao.DeptDAO;
import com.yxcz.model.AddDeptForm;
import com.yxcz.model.Dept;
import com.yxcz.model.JsonDept;
import com.yxcz.model.Menu;
import com.yxcz.model.UpdateDeptForm;
import com.yxcz.service.DeptService;

@Service
public class DeptServiceImpl implements DeptService {

	@Resource
	private DeptDAO DeptDAO;

	@Override
	public ArrayList<Dept> list(String keyword) {

		return null;
	}

	@Override
	public ArrayList<Dept> list() {

		return DeptDAO.list();
	}

	@Override
	public Dept getDept(Integer id) {

		return DeptDAO.find(id);
	}

	@Override
	public void deleteById(Integer id) {
		DeptDAO.delete(DeptDAO.find(id));
	}

	@Override
	public void update(Dept form) {
		DeptDAO.save(form);

	}

	@Override
	public void add(Dept form) throws Exception {
		DeptDAO.add(form);

	}

	@Override
	public Dept find(Integer id) {

		return DeptDAO.find(id);
	}

	@Override
	public String jsonList() {

		@SuppressWarnings("unchecked")
		ArrayList<Object[]> depts = (ArrayList<Object[]>) DeptDAO
				.query("select dept.name,dept.id,dept.pDept.id from Dept dept order by sequence", new HashMap<String, Object>());
		
		ArrayList<JsonDept> jsonDepts= new ArrayList<>();
		
		for (Object[] dept : depts) {
			JsonDept jsondept = new JsonDept();
			jsondept.setName((String) dept[0]);
			jsondept.setId((int) dept[1]);
			jsondept.setPid(dept[2] == null ? 0 : (int) dept[2]);
			jsonDepts.add(jsondept);
		}
		
		ObjectMapper objectMapper = new ObjectMapper();
		String mapJson;
		try {
			mapJson = objectMapper.writeValueAsString(jsonDepts);
			return mapJson;
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			return null;
		}

	}

	@Override
	public void delete(Integer id) {
		DeptDAO.delete(DeptDAO.find(id));
		
	}

	@Override
	public void update(UpdateDeptForm form) {
		
		Dept dept = DeptDAO.find(form.getId());
		
		dept.setName(form.getName());
		dept.setSequence(form.getSequence());
		dept.setShortName(form.getShortName());
		dept.setStatus(form.isStatus());
		DeptDAO.save(dept);
		
	}

	@Override
	public void add(AddDeptForm form) throws Exception {
		
		Dept pDept = DeptDAO.find(form.getPid());
		Dept dept = new Dept();
		dept.setpDept(pDept);
		dept.setName(form.getName());
		dept.setSequence(form.getSequence());
		dept.setShortName(form.getShortName());
		dept.setStatus(form.isStatus());
		DeptDAO.add(dept);
		
	}

}
